package com.ruyiadmin.springboot.web_api.controllers.framework_controllers;

import com.ruyiadmin.springboot.web_api.annotations.framework.AllowAnonymous;
import com.ruyiadmin.springboot.web_api.annotations.framework.SimpleRateLimiter;
import com.ruyiadmin.springboot.common_infrastructure.properties.JwtSettings;
import com.ruyiadmin.springboot.common_infrastructure.classes.CaptchaPicture;
import com.ruyiadmin.springboot.common_infrastructure.models.ActionResponseResult;
import com.ruyiadmin.springboot.common_infrastructure.components.system.RuYiRedisContext;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 系统验证码服务 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-16
 */
@RestController
@RequestMapping("/RuYiAdminCaptcha")
@Api(tags = "系统验证码服务")
@EnableConfigurationProperties({JwtSettings.class})
@RequiredArgsConstructor
public class RuYiAdminCaptchaController {

    //region 服务私有属性

    private final JwtSettings jwtSettings;
    private final RuYiRedisContext redisContext;

    //endregion

    //region 获取系统验证码

    @GetMapping("/GetCaptcha")
    @ApiOperation(value = "获取系统验证码")
    @AllowAnonymous
    @SimpleRateLimiter(value = 1.0)
    public ActionResponseResult getCaptcha() throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResponseResult> future = CompletableFuture.supplyAsync(() -> {
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(200, 50, 3);
            CaptchaPicture adminCaptcha = new CaptchaPicture();
            adminCaptcha.setId(UUID.randomUUID().toString());
            // 缓存用于登录校验
            this.redisContext.set(adminCaptcha.getId(), captcha.text(), this.jwtSettings.getSaltExpiration());
            adminCaptcha.setCaptchaValue(captcha.toBase64());
            return ActionResponseResult.success(adminCaptcha);
        });
        return future.get();
    }

    //endregion

}
